<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 站点模块权限配置 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\model;

use think\Cache;
use think\Db;
use think\Model;

class SiteModuleAuthority extends Model {
    const CACHE_KEY = "core.SiteModuleAuthority.";

    /**
     * 增加模块权限
     *
     * @param $mid
     * @param $authorities
     */
    public static function createAuthorities($mid, $authorities) {
        foreach ($authorities as $authority) {
            $data = [
                'module_id' => $mid,
                'title' => $authority['title'],
                'key' => strtolower($authority['key']),
                'group' => $authority['group'],
                'type' => $authority['type'],
                'defaultval' => $authority['defaultval']
            ];
            self::create($data);
        }
        Cache::rm(self::CACHE_KEY . $mid);
    }

    /**
     * 获取模块的权限点
     *
     * @param $mid
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getAuthorities($mid) {
        $cacheKey = self::CACHE_KEY . $mid;
        $authorities = Cache::get($cacheKey);
        if (empty($authorities)) {
            $authorities = Db::name("site_module_authority")->where(['module_id' => $mid])->select();
            Cache::set($cacheKey, $authorities, 86400);
        }
        return $authorities;
    }

    /**
     * 删除模块相关的全部菜单和入口
     *
     * @param $mid
     * @return int
     */
    public static function deleteByMid($mid) {
        $query = new self();
        $ret = $query->where(['module_id' => $mid])->delete();
        Cache::rm(self::CACHE_KEY . $mid);
        return $ret;
    }
}